<?php

namespace app\index\controller;

use app\index\model\Gallery;
use app\index\model\User;

/**
 * Class Collect
 * @package app\index\controller
 */
class Collect extends Base
{
    /**
     * 我的收藏页面
     */
    public function index()
    {
        $collects = model('collect')->where('user_id', session('user.id'))->select();
        $galleries = [];
        foreach ($collects as $collect) {
            $gallery = Gallery::get($collect->gallery_id);
            $image = \app\index\model\Image::get($gallery->cover_id);
            $gallery['cover'] = $image->path;
            $user = User::get($gallery->user_id);
            $gallery['author'] = $user->nickname;
            array_push($galleries, $gallery);
        }
        $this->assign('galleries', $galleries);
        return view();
    }

    /**
     * 图库详情页面
     */
    public function show($id)
    {
        $gallery = Gallery::get($id);
        if (!$gallery) {
            $this->error('图库不存在！');
        }
        if ($gallery->status != 1) {
            $collect = model('collect')
                ->where(['user_id' => session('user.id'), 'gallery_id' => $id])->find();
            $collect->delete();
            $this->error('图库已被取消发布！');
        }
        $user = User::get($gallery->user_id);
        $gallery['author'] = $user->nickname;
        $this->assign('gallery', $gallery);
        $images = model('image')->where('gallery_id', $id)->select();
        $this->assign('images', $images);
        return view();
    }

    /**
     * 收藏或取消收藏图库
     */
    public function collect($id)
    {
        $gallery = Gallery::get($id);
        if (!$gallery) {
            $this->error('图库不存在！');
        }
        $collect = model('collect')
            ->where(['user_id' => session('user.id'), 'gallery_id' => $id])->find();
        $collect->delete();
        $this->success('取消收藏成功！', 'index');
    }
}
